package be.donovan.model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;

@Entity
public class Invoice implements Serializable{

	@Id
	Long id;
	@ManyToOne
	private PersonInfo billingAddress;
	@OneToMany
	private List<InvoiceItem> items;

	/**
	 * Constructs an invoice.
	 * 
	 * @param anAddress
	 *            the billing address
	 */
	public Invoice(PersonInfo anAddress) {
		items = new ArrayList<InvoiceItem>();
		billingAddress = anAddress;
	}

	/**
	 * Adds a charge for a product to this invoice.
	 * 
	 * @param aProduct
	 *            the product that the customer ordered
	 * @param quantity
	 *            the quantity of the product
	 */
	public void add(Product aProduct, int quantity) {
		InvoiceItem anItem = new InvoiceItem(aProduct, quantity);
		items.add(anItem);
	}

	/**
	 * Formats the invoice.
	 * 
	 * @return the formatted invoice
	 */
	public String format() {
		String r = "                     I N V O I C E\n\n"
				+ billingAddress.format()
				+ "\n\nDescription                   Price  Qty  Total\n";
		for (int i = 0; i < items.size(); i++) {
			InvoiceItem nextItem = (InvoiceItem) items.get(i);
			r = r + nextItem.format() + "\n";
		}

		r = r + "\nAMOUNT DUE: $" + getAmountDue();

		return r;
	}

	/**
	 * Computes the total amount due.
	 * 
	 * @return the amount due
	 */
	public double getAmountDue() {
		double amountDue = 0;
		for (int i = 0; i < items.size(); i++) {
			InvoiceItem nextItem = (InvoiceItem) items.get(i);
			amountDue = amountDue + nextItem.getTotalPrice();
		}
		return amountDue;
	}

}
